package cn.iot.sys.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.iot.common.dto.ResultMsg;
import cn.iot.sys.dao.SysClassDao;
import cn.iot.sys.dao.SysLeaveApplicationDao;
import cn.iot.sys.entity.SysClass;
import cn.iot.sys.entity.SysLeaveApplication;
import cn.iot.sys.service.SysLeaveApplicationService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysLeaveApplicationServiceImpl implements SysLeaveApplicationService {
    @Resource
    private SysLeaveApplicationDao sysLeaveApplicationDao;
    @Resource
    private SysClassDao sysClassDao;
//    @Resource
//    private RuntimeService runtimeService;
    private ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
    private RuntimeService runtimeService = processEngine.getRuntimeService();
    private TaskService taskService = processEngine.getTaskService();

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Override
    public ResultMsg getSysLeaveApplicationList(Map<String, Object> map) {
        logger.info("SysLeaveApplicationServiceImpl getSysLeaveApplicationList map{}",map);
        int pageNum = Integer.parseInt((String)map.get("pageNum"));
        int pageSize = Integer.parseInt((String)map.get("pageSize"));
        String leaveTypeName = (String)map.get("leaveTypeName");
        String createDate = (String)map.get("createDate");
        String applicationNumber = (String)map.get("applicationNumber");
        int start = (pageNum-1)*pageSize;
        if (StrUtil.isNotEmpty(leaveTypeName)||StrUtil.isNotEmpty(createDate)||StrUtil.isNotEmpty(applicationNumber)){
            start = 0;
        }
        map.put("start",start);
        map.remove("pageSize");
        map.put("pageSize",pageSize);
        List<SysLeaveApplication> sysLeaveApplicationList = sysLeaveApplicationDao.getSysLeaveApplicationList(map);
        int count = sysLeaveApplicationDao.getCount(map);
        int pageCount;
        if (count>0){
            pageCount = count%pageSize==0? count/pageSize:count/pageSize+1;
        }else {
            pageCount = 0;
        }
        map.put("sysLeaveApplicationList",sysLeaveApplicationList);
        map.put("pageCount",pageCount);
        ResultMsg msg = new ResultMsg(200,"成功",map);
        return msg;
    }

    @Override
    public ResultMsg getCount(Map<String, Object> map) {
        logger.info("SysLeaveApplicationServiceImpl getCount map{}",map);
        int count = sysLeaveApplicationDao.getCount(map);
        ResultMsg msg;
        if (count>0){
            msg = new ResultMsg(200,"成功",count);
            return msg;
        }
        msg = new ResultMsg(500,"失败",count);
        return msg;
    }

    @Override
    public ResultMsg addSysLeaveApplication(SysLeaveApplication sysLeaveApplication) {
        logger.info("SysLeaveApplicationServiceImpl addSysLeaveApplication sysLeaveApplication{}",sysLeaveApplication);
        String applicationNumber = sysLeaveApplication.getApplicationNumber();
        //获取班主任名称
        SysClass sysClass = sysClassDao.viewSysClassById(sysLeaveApplication.getClassId());
        String teacherName = sysClass.getTeacherName();
        sysLeaveApplication.setApprover(teacherName);
        //执行申请
        int count = sysLeaveApplicationDao.addSysLeaveApplication(sysLeaveApplication);
        ResultMsg msg;
        if (count>0){
            Map<String,Object> map = new HashMap<>();
            map.put("applyCode",applicationNumber);
            map.put("application","sid-9ea8851c-8365-4fca-ba9d-a53effaaffd6");
            map.put("teacherName",teacherName);
            map.put("leaveTotalTime",sysLeaveApplication.getTotalDay());
            ProcessInstance sq = runtimeService.startProcessInstanceByKey("leave", map);
            if (sq != null){
                sysLeaveApplication.setProcessId(sq.getId());
                sysLeaveApplicationDao.updProcessId(sysLeaveApplication);
                msg = new ResultMsg(200,"添加成功,已进入审批",null);
                return msg;
            }
            return new ResultMsg(500,"添加成功,已进入审批失败",null);
        }
        msg = new ResultMsg(500,"失败",count);
        return msg;
    }

    @Override
    public ResultMsg updSysLeaveApplication(int id) {
        logger.info("SysLeaveApplicationServiceImpl updSysLeaveApplication id{}",id);
        int count = sysLeaveApplicationDao.updSysLeaveApplication(id);
        ResultMsg msg;
        if (count>0){
            // 删除对应的流程实例
            SysLeaveApplication application = sysLeaveApplicationDao.selectById(id);
            if (application != null && application.getProcessId() != null) {
                runtimeService.deleteProcessInstance(application.getProcessId(), "申请已撤销");
            }
            msg = new ResultMsg(200,"成功",count);
            return msg;
        }
        msg = new ResultMsg(500,"失败",count);
        return msg;
    }

    @Override
    public ResultMsg getPendingList(Map<String, Object> map) {
        logger.info("SysLeaveApplicationServiceImpl getPendingList map{}",map);
        int pageNum = Integer.parseInt((String)map.get("pageNum"));
        int pageSize = Integer.parseInt((String)map.get("pageSize"));
        int start = (pageNum-1)*pageSize;
        map.remove("pageSize");
        map.put("pageSize",pageSize);
        map.put("start",start);
        List<SysLeaveApplication> pendingList = sysLeaveApplicationDao.getPendingList(map);
        int count = sysLeaveApplicationDao.getApplicationCount();
        int pageCount;
        if (count>0){
            pageCount = count%pageSize==0? count/pageSize:count/pageSize+1;
        }else {
            pageCount = 0;
        }
        map.put("pendingList",pendingList);
        map.put("pageCount",pageCount);
        ResultMsg msg = new ResultMsg(200,"成功",map);
        return msg;
    }

    @Override
    public ResultMsg getProcessedList(Map<String, Object> map) {
        logger.info("SysLeaveApplicationServiceImpl getPendingList map{}",map);
        int pageNum = Integer.parseInt((String)map.get("pageNum"));
        int pageSize = Integer.parseInt((String)map.get("pageSize"));
        int start = (pageNum-1)*pageSize;
        map.remove("pageSize");
        map.put("pageSize",pageSize);
        map.put("start",start);
        List<SysLeaveApplication> processedList = sysLeaveApplicationDao.getProcessedList(map);
        int count = sysLeaveApplicationDao.getApplicationCountByStatus();
        int pageCount;
        if (count>0){
            pageCount = count%pageSize==0? count/pageSize:count/pageSize+1;
        }else {
            pageCount = 0;
        }
        map.put("processedList",processedList);
        map.put("pageCount",pageCount);
        ResultMsg msg = new ResultMsg(200,"成功",map);
        return msg;
    }
    @Override
    public ResultMsg approve(SysLeaveApplication sysLeaveApplication) {
        try {
            // 获取流程实例ID
            String processInstanceId = sysLeaveApplication.getProcessId();
            Task task = taskService.createTaskQuery()
                    .processInstanceId(processInstanceId)
                    .singleResult();
            int totalDay = sysLeaveApplication.getTotalDay();
            if (task != null) {
                String currentApprover = task.getAssignee();
                sysLeaveApplication.setApprover(currentApprover);
                sysLeaveApplicationDao.updApprover(sysLeaveApplication);
                taskService.complete(task.getId());
                if (totalDay>3) {
                    sysLeaveApplication.setApprover("年级组长");
                    sysLeaveApplicationDao.updApprover(sysLeaveApplication);
                }
                return new ResultMsg(200, "审批已处理", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResultMsg(500, "审批失败", null);
    }


    @Override
    public ResultMsg reject(SysLeaveApplication sysLeaveApplication) {
        try {
            String processInstanceId = sysLeaveApplication.getProcessId();
            Task task = taskService.createTaskQuery()
                    .processInstanceId(processInstanceId)
                    .singleResult();

            if (task != null) {
                Map<String, Object> variables = new HashMap<>();
                int leaveTotalTime = sysLeaveApplication.getTotalDay();

                // 将 leaveTotalTime 添加到变量中
                variables.put("leaveTotalTime", leaveTotalTime);
                variables.put("approvalStatus", "rejected");
                taskService.complete(task.getId(), variables);

                // 班主任驳回，直接更新状态
                sysLeaveApplication.setStatus(3); // 状态为驳回
                sysLeaveApplicationDao.updateById(sysLeaveApplication);

                return new ResultMsg(200, "审批已驳回", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResultMsg(500, "审批失败", null);
    }
}
